<?php

require_once 'parser.php';

if(! isset($_GET['action'])) {
    die('Bad request');
}
$function = $_GET['action'];
if (! function_exists($function)) {
    die('Invalid Action');
}

call_user_func($function);

function parseLink() {
  
    if(! (isset($_POST['link']) || isset($_POST['pattern']))) {
        die('moar data, plz');
    }
    
    $s = new Parser($_POST['link']);
    $code = nl2br($_POST['pattern']);
    $code = str_replace('{artists}', implode(', ', $s->releaseArtists), $code);
    $code = str_replace('{title}', $s->releaseTitle, $code);
    $code = str_replace('{genres}', implode(', ', $s->genres), $code);
    $code = str_replace('{release_date}', $s->releaseDate, $code);
    $code = str_replace('{label}', $s->label, $code);
    $code = str_replace('{catalog}', $s->catalog, $code);
    $code = str_replace('{review}', $s->review, $code);
    $code = str_replace('{url}', $s, $code);
     
     
    $m = preg_match_all('/{artists\|(.*)\|\"(.*)\"}/imu', $code, $results);
    for ($i = 0; $i < count($results[0]); $i++) {
        $res = '';
        $outArtists = array();
        foreach($s->releaseArtists as $artist) {
            $outArtists[] = trim(str_replace('[a]', $artist, $results[1][$i]));
        }
        $artists = implode($results[2][$i], $outArtists);
        $code = str_replace($results[0][$i], $artists, $code);
    }
     
    $tracklist = '';
    if(preg_match('/{{tracklist}}(.*){{\/tracklist}}/isU', $code, $mm) == true) {
        
        $str = trim($mm[1]);
        
        foreach($s->tracklist as $index => $track) {
            
            $track = $s->track($index);
            $newTrack = str_replace('{track_num}', $index, $str);
            
            $newTrack = preg_replace('/{track_num\|([0-9])}/e', "zeros(" . $index . ", '\\1')", $newTrack);
            
            $newTrack = str_replace('{track_title}', $track->title, $newTrack);
            $newTrack = str_replace('{track_length}', $track->length, $newTrack);
            $newTrack = str_replace('{track_artists}', implode(', ', $track->artists), $newTrack);

            $m = preg_match_all('/{track_artists\|(.*)\|\"(.*)\"}/imu', $code, $results);
            for ($i = 0; $i < count($results[0]); $i++) {
                $outArtists = array();
                foreach($track->artists as $artist) {
                    $outArtists[] = trim(str_replace('[a]', $artist, $results[1][$i]));
                }
                $artists = implode($results[2][$i], $outArtists);
                $newTrack = str_replace($results[0][$i], $artists, $newTrack);
            }
            
            $tracklist .= $newTrack;
        }
    }
    
    $code = preg_replace('/{{tracklist}}(.*){{\/tracklist}}/isU', $tracklist, $code);
    
    echo $code;
}
